/*
 * Alloy Analyzer
 * Copyright (c) 2002 Massachusetts Institute of Technology
 *
 * The Alloy Analyzer is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The Alloy Analyzer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with the Alloy Analyzer; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package alloy.bool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.StringTokenizer;

/**
 * Miscellaneous boolean-related utilities.
 */
public class BoolUtil {

    /** Determine the number of clauses in a CNF file */
    public static int getCnfNumClauses(File cnfFileHandle_) throws IOException {
        LineNumberReader r = new LineNumberReader(new BufferedReader(new FileReader(cnfFileHandle_)));
        String line = null;

        do {
            line = r.readLine();
            if (line!=null && line.startsWith("p cnf")) {
            StringTokenizer st = new StringTokenizer(line);
            if (st.countTokens() != 4) throw new IOException("invalid cnf file header");
            st.nextToken(); st.nextToken(); st.nextToken();
            int numClauses = 0;
            try {
                numClauses = Integer.parseInt(st.nextToken());
            } catch (NumberFormatException nfe_) {
                throw new IOException("invalid clause count in cnf header");
            }
            r.close();
            return numClauses;
            }
        } while (line != null);

        r.close();
        throw new IOException("cnf file does not have a 'p cnf' header");
    }

    public static void main(String[] args) {
        System.out.println("cnf clauses in " + args[0] + ": ");
        try {
            System.out.println(getCnfNumClauses(new File(args[0])));
        } catch (IOException ioe_) {
            System.out.println("ioexception: " + ioe_);
        }
    }
}

